<template>
  <div class="role-management">
    <div class="page-header">
      <h2>角色管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增角色
        </el-button>
      </div>
    </div>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>角色列表</span>
          <div class="header-actions">
            <el-select
              v-model="filters.type"
              placeholder="角色类型"
              style="width: 120px"
              clearable
              @change="handleFilter"
            >
              <el-option label="系统角色" value="system" />
              <el-option label="业务角色" value="business" />
            </el-select>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索角色名称"
              style="width: 200px"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table :data="filteredRoles" v-loading="loading">
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="code" label="角色编码" width="150" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 'system' ? 'primary' : 'success'">
              {{ row.type === 'system' ? '系统角色' : '业务角色' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="permissions" label="权限数量" width="100">
          <template #default="{ row }">
            <el-tag size="small">
              {{ row.permissions.length }}个
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="info" size="small" @click="handleViewPermissions(row)">
                权限
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑角色' : '新增角色'"
      width="600px"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="角色类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio value="system">系统角色</el-radio>
            <el-radio value="business">业务角色</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.type === 'business'" label="等级" prop="level">
          <el-select v-model="formData.level" placeholder="请选择等级" clearable>
            <el-option label="2级" :value="2" />
            <el-option label="3级" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <div class="permissions-section">
            <el-checkbox-group v-model="formData.permissions">
              <div class="permission-category">
                <h4>系统权限</h4>
                <el-checkbox value="user:read">用户查看</el-checkbox>
                <el-checkbox value="user:write">用户管理</el-checkbox>
                <el-checkbox value="role:read">角色查看</el-checkbox>
                <el-checkbox value="role:write">角色管理</el-checkbox>
                <el-checkbox value="department:read">部门查看</el-checkbox>
                <el-checkbox value="department:write">部门管理</el-checkbox>
                <el-checkbox value="contractor:read">承包商查看</el-checkbox>
                <el-checkbox value="contractor:write">承包商管理</el-checkbox>
              </div>
              <div class="permission-category">
                <h4>JSA权限</h4>
                <el-checkbox value="jsa:read">JSA查看</el-checkbox>
                <el-checkbox value="jsa:write">JSA创建</el-checkbox>
                <el-checkbox value="jsa:review">JSA审核</el-checkbox>
                <el-checkbox value="jsa:approve">JSA批准</el-checkbox>
                <el-checkbox value="jsa:review_level_2">JSA 2级审核</el-checkbox>
                <el-checkbox value="jsa:review_level_3">JSA 3级审核</el-checkbox>
                <el-checkbox value="jsa:approve_level_2">JSA 2级批准</el-checkbox>
                <el-checkbox value="jsa:approve_level_3">JSA 3级批准</el-checkbox>
              </div>
              <div class="permission-category">
                <h4>作业许可权限</h4>
                <el-checkbox value="permit:read">许可查看</el-checkbox>
                <el-checkbox value="permit:apply">许可申请</el-checkbox>
                <el-checkbox value="permit:review">许可审核</el-checkbox>
                <el-checkbox value="permit:approve">许可批准</el-checkbox>
                <el-checkbox value="permit:approve_level_2">许可 2级批准</el-checkbox>
                <el-checkbox value="permit:approve_level_3">许可 3级批准</el-checkbox>
              </div>
              <div class="permission-category">
                <h4>业务权限</h4>
                <el-checkbox value="area:manage">区域管理</el-checkbox>
                <el-checkbox value="safety:supervise">安全监督</el-checkbox>
                <el-checkbox value="safety:inspect">安全检查</el-checkbox>
                <el-checkbox value="operation:execute">作业执行</el-checkbox>
                <el-checkbox value="technical:advise">技术指导</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleSubmit">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限查看对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="角色权限"
      width="500px"
    >
      <div class="permission-list">
        <h4>{{ currentRole?.name }}的权限：</h4>
        <el-tag
          v-for="permission in currentRole?.permissions"
          :key="permission"
          size="small"
          class="permission-tag"
        >
          {{ getPermissionName(permission) }}
        </el-tag>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { useRoleStore } from '@/stores/role'
import type { Role } from '@/types'

const roleStore = useRoleStore()

const loading = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const isEdit = ref(false)
const searchKeyword = ref('')
const formRef = ref<FormInstance>()

const roles = ref<Role[]>([])
const currentRole = ref<Role | null>(null)

const filters = reactive({
  type: ''
})

const formData = reactive({
  name: '',
  code: '',
  description: '',
  type: 'system' as 'system' | 'business',
  level: undefined as number | undefined,
  permissions: [] as string[]
})

const formRules: FormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择角色类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' }
  ]
}

// 过滤后的角色列表
const filteredRoles = computed(() => {
  let result = roles.value

  if (searchKeyword.value) {
    result = result.filter(role =>
      role.name.includes(searchKeyword.value) ||
      role.code.includes(searchKeyword.value)
    )
  }

  if (filters.type) {
    result = result.filter(role => role.type === filters.type)
  }

  return result
})


// 获取权限名称
const getPermissionName = (permission: string) => {
  const permissionMap: Record<string, string> = {
    'user:read': '用户查看',
    'user:write': '用户管理',
    'role:read': '角色查看',
    'role:write': '角色管理',
    'department:read': '部门查看',
    'department:write': '部门管理',
    'contractor:read': '承包商查看',
    'contractor:write': '承包商管理',
    'jsa:read': 'JSA查看',
    'jsa:write': 'JSA创建',
    'jsa:review': 'JSA审核',
    'jsa:approve': 'JSA批准',
    'jsa:review_level_2': 'JSA 2级审核',
    'jsa:review_level_3': 'JSA 3级审核',
    'jsa:approve_level_2': 'JSA 2级批准',
    'jsa:approve_level_3': 'JSA 3级批准',
    'permit:read': '许可查看',
    'permit:apply': '许可申请',
    'permit:review': '许可审核',
    'permit:approve': '许可批准',
    'permit:approve_level_2': '许可 2级批准',
    'permit:approve_level_3': '许可 3级批准',
    'area:manage': '区域管理',
    'safety:supervise': '安全监督',
    'safety:inspect': '安全检查',
    'operation:execute': '作业执行',
    'technical:advise': '技术指导'
  }
  return permissionMap[permission] || permission
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    roles.value = await roleStore.getAllRoles()
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  // 搜索逻辑在computed中处理
}

// 过滤
const handleFilter = () => {
  // 过滤逻辑在computed中处理
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  currentRole.value = null
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: Role) => {
  isEdit.value = true
  currentRole.value = row
  Object.assign(formData, {
    name: row.name,
    code: row.code,
    description: row.description,
    type: row.type,
    level: row.level,
    permissions: [...row.permissions]
  })
  dialogVisible.value = true
}

// 查看权限
const handleViewPermissions = (row: Role) => {
  currentRole.value = row
  permissionDialogVisible.value = true
}

// 删除
const handleDelete = async (row: Role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await roleStore.deleteRole(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (isEdit.value && currentRole.value) {
      await roleStore.updateRole(currentRole.value.id, formData)
      ElMessage.success('更新成功')
    } else {
      await roleStore.createRole(formData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    code: '',
    description: '',
    type: 'system',
    level: undefined,
    permissions: []
  })
  formRef.value?.resetFields()
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.role-management {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 8px;
      }
    }
    
    .action-buttons {
      display: flex;
      gap: 8px;
    }
  }
  
  .permissions-section {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 16px;
    
    .permission-category {
      margin-bottom: 16px;
      
      h4 {
        margin: 0 0 8px 0;
        color: #606266;
        font-size: 14px;
      }
      
      .el-checkbox {
        display: block;
        margin-bottom: 8px;
      }
    }
  }
  
  .permission-list {
    h4 {
      margin: 0 0 16px 0;
      color: #333;
    }
    
    .permission-tag {
      margin-right: 8px;
      margin-bottom: 8px;
    }
  }
}
</style>